package com.zrrd.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.zrrd.reggie.bean.Employee;
import com.zrrd.reggie.bean.User;
import com.zrrd.reggie.common.R;
import com.zrrd.reggie.common.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;

import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
*
* 检查用户是否已经完成登录
*
* */
@Slf4j

//标注当前类是一个拦截器
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {


    //路径匹配工具对象
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();


    //拦截的方法
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //将请求对象进行类型转换
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        //获取本次请求的URI
        String url = req.getRequestURI();
        log.info("当前请求地址===>" + url);


        //定义不需要拦截的请求路径数组
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };

        //判断本次请求是否需要处理
       // boolean isCheckUrl = isCheckUrl(urls,url);

        //判断当前请求的路径是否匹配方法
        if(isCheckUrl(urls,url)){
            //如果不需要处理 放行
           chain.doFilter(req,res);
           return;
        }


        //从Session中获得登录时候存入的员工id
        Long empId = (Long) req.getSession().getAttribute("emp");
        //判断id
        if (empId != null){
            //将当前登录的用户id存入到线程变量中
            ThreadLocalUtil.setCurrentId(empId);
            //放行
            chain.doFilter(req,res);
            return;
        }

        //从session获取移动端用户登录时候存入的用户信息
        User user = (User) req.getSession().getAttribute("user");
        if (user != null){
            //将当前用户的id存入到线程变量当中
            ThreadLocalUtil.setCurrentId(user.getId());
            //放行
            chain.doFilter(req,res);
            return;
        }

        //如果能走到这里 就代表未登录 给前端响应结果 告知未登录
        res.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;

    }

    //判断路径是否匹配的方法
    private boolean isCheckUrl(String[] urls,String url) {
        //遍历路径数组
        for (String s : urls) {
            boolean match = PATH_MATCHER.match(s, url);
            if (match) {
                return true;
            }
        }
        return false;

    }
}

